package cre.tool.core;

import cre.tool.domain.Album;
import cre.tool.domain.AlbumInfo;
import cre.tool.exception.ToolException;
import cre.tool.util.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author penglai
 * @Date 2017/2/24.
 */
public class FileReader {

    public Map<Integer, List<Integer>> readFile() throws Exception {
        Map<String, Integer> categoryMap = Configuration.getCategoryMap();

        if (categoryMap == null || categoryMap.size() == 0) {
            throw new ToolException("请设置文件：" + Configuration.SUBS_CONFIG);
        }
        throw new UnsupportedOperationException();
    }

    public Map<Integer, List<Integer>> readFile(String categoryId, Map<Integer, String> categoryMap, boolean autoImportSub) throws Exception {
        Map<String, Integer> categoryMap2 = wrapIntegerStringMap(categoryMap);
        return readFileInternal(categoryId, categoryMap2, autoImportSub);
    }

    private Map<String, Integer> wrapIntegerStringMap(Map<Integer, String> categoryMap) {
        Map<String, Integer> categoryMap2 = new HashMap<>();
        for (Map.Entry<Integer, String> entry : categoryMap.entrySet()) {
            categoryMap2.put(entry.getValue(), entry.getKey());
        }
        return categoryMap2;
    }

    public Map<Integer, List<Integer>> readFileInternal(String categoryId, Map<String, Integer> categoryMap,
                                                        boolean autoImportSub) throws Exception {
        Map<Integer, List<Integer>> ret = null;
        InputStream is = null;
        try {
            ret = new HashMap<>();
            Map<String, List<Integer>> map = new HashMap<>();

            is = new FileInputStream(TOOL_HOME + FILE_DIR + "/" + IMPORT_FILE);
            Workbook wb = new XSSFWorkbook(is);
            Sheet sheet = wb.getSheetAt(0);

            int i = 0;
            for (Row row : sheet) {
                if (i == 0) {
                    i++;
                    continue;
                }
                Cell cell = row.getCell(0);
                String val = cell.getStringCellValue();

                cell = row.getCell(1);
                int val2 = (int) cell.getNumericCellValue();

                if (StringUtils.isEmpty(val) || val2 <= 0) {
                    break;
                }
                i++;

                List<Integer> albums = map.get(val);
                if (albums == null) {
                    albums = new ArrayList<>();
                    map.put(val, albums);
                }

                albums.add(Integer.valueOf(val2));
            }

            if (autoImportSub && StringUtils.isNotEmpty(categoryId)) {
                // 自动导入二级分类

                List<String> subs = new ArrayList<>();
                DbHandler dbHandler = new DbHandler();

                for (String s : map.keySet()) {
                    if (!categoryMap.containsKey(s)) {
                        subs.add(s);
                    }
                }

                dbHandler.insertSubCategory(categoryId, subs);
                Map<Integer, String> subMaps = dbHandler.selectSubMaps(categoryId);
                categoryMap = wrapIntegerStringMap(subMaps);
            }

            for (String s : map.keySet()) {
                Integer ci = categoryMap.get(s);
                if (ci != null) {
                    ret.put(ci, map.get(s));
                }
            }
        } catch (Exception e) {
            throw new ToolException(e);
        } finally {
            if (is != null) {
                is.close();
            }
        }
        return ret;
    }

    public List<String> readSubFile() throws Exception {
        List<String> ret = new ArrayList<>();
        InputStream is = null;
        try {
            is = new FileInputStream(TOOL_HOME + FILE_DIR + "/" + SUB_FILE);
            Workbook wb = new XSSFWorkbook(is);
            Sheet sheet = wb.getSheetAt(0);

            int i = 0;
            for (Row row : sheet) {
                Cell cell = row.getCell(0);
                String val = cell.getStringCellValue();

                if (StringUtils.isNotEmpty(val)) {
                    ret.add(val);
                }
            }
        } catch (Exception e) {
            throw new ToolException(e);
        } finally {
            if (is != null) {
                is.close();
            }
        }
        return ret;
    }

    public void writeSubMaps(Map<Integer, String> subMaps) throws IOException {
        FileWriter writer = null;
        try {
            writer = FileUtils.gainFileWriter(TOOL_HOME + "/" + CONF_DIR + "/", Configuration.SUBS_CONFIG);
            for (Map.Entry<Integer, String> entry : subMaps.entrySet()) {
                writer.write(entry.getKey() + "=" + entry.getValue() + "\n");
            }
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

    public AlbumInfo readAlbumInfo() throws Exception {
        AlbumInfo ret = new AlbumInfo();
        InputStream is = null;
        try {
            is = new FileInputStream(TOOL_HOME + FILE_DIR + "/" + ALBUM_INFO_FILE);
            Workbook wb = new XSSFWorkbook(is);
            Sheet sheet = wb.getSheetAt(0);

            Row fr = sheet.getRow(0);
            Cell fc = fr.getCell(0);

            int type = fc.getCellType();
            List<String> vals = new ArrayList<>();

            ret.setType(type);
            ret.setAlbums(vals);

            for (Row row : sheet) {
                Cell cell = row.getCell(0);
                String val = "";

                switch (cell.getCellType()) {
                    case XSSFCell.CELL_TYPE_NUMERIC:
                        val = String.valueOf((int) cell.getNumericCellValue());
                    case XSSFCell.CELL_TYPE_STRING:
                        val = StringUtils.trim(cell.getStringCellValue());
                }
                vals.add(val);
            }
        } catch (Exception e) {
            throw new ToolException(e);
        } finally {
            if (is != null) {
                is.close();
            }
        }
        return ret;
    }

    public void writeAlbums(String categoryId, List<Album> albums, String title) throws IOException {
        OutputStream os = null;
        FileWriter writer = null;
        try {
            String filename = EXPORT_FILE;
            if (StringUtils.isNotEmpty(title)) {
                filename = title + EXCEL_SUFFIX;
            }

            Workbook wb = new XSSFWorkbook();
            Sheet sheet = wb.createSheet();

            for (int i = 0; i < albums.size(); i++) {
                Album album = albums.get(i);
                Row row = sheet.createRow(i);

                row.createCell(0).setCellValue(album.getId());
                row.createCell(1).setCellValue(album.getTitle());
                row.createCell(2).setCellValue(album.getInfo());
            }

            File dir = new File(TOOL_HOME + FILE_DIR + "/" + categoryId);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            os = new FileOutputStream(new File(dir, filename));
            wb.write(os);
        } finally {
            if (os != null) {
                os.close();
            }
        }
    }

    public void writeAlbums(List<Album> albums) throws IOException {
        OutputStream os = null;
        FileWriter writer = null;
        try {
            String filename = ALBUM_INFO_EXPORT_FILE;
            Workbook wb = new XSSFWorkbook();
            Sheet sheet = wb.createSheet();
            createHeader(sheet);

            for (int i = 0; i < albums.size(); i++) {
                Album album = albums.get(i);
                Row row = sheet.createRow(i + 1);

                row.createCell(0).setCellValue(album.getId());
                row.createCell(1).setCellValue(album.getTitle());
                row.createCell(2).setCellValue(album.getInfo());
                row.createCell(3).setCellValue(album.getStatus());
                row.createCell(4).setCellValue(album.getIsDel());

                row.createCell(5).setCellValue(album.getCollectCount());
                row.createCell(6).setCellValue(album.getRealCollectCount());
                row.createCell(7).setCellValue(album.getPlayCount());
                row.createCell(8).setCellValue(album.getRealPlayCount());
                row.createCell(9).setCellValue(album.getDownloadCount());
                row.createCell(10).setCellValue(album.getRealDownloadCount());
                row.createCell(11).setCellValue(album.getLikeCount());
                row.createCell(12).setCellValue(album.getRealLikeCount());
            }

            File dir = new File(TOOL_HOME + FILE_DIR + "/");
            if (!dir.exists()) {
                dir.mkdirs();
            }
            os = new FileOutputStream(new File(dir, filename));
            wb.write(os);
        } finally {
            if (os != null) {
                os.close();
            }
        }
    }

    private void createHeader(Sheet sheet) {
        Row row = sheet.createRow(0);
        row.createCell(0).setCellValue("id");
        row.createCell(1).setCellValue("title");
        row.createCell(2).setCellValue("info");
        row.createCell(3).setCellValue("status");
        row.createCell(4).setCellValue("is_del");
        row.createCell(5).setCellValue("collect_count");
        row.createCell(6).setCellValue("real_collect_count");
        row.createCell(7).setCellValue("play_count");
        row.createCell(8).setCellValue("real_play_count");
        row.createCell(9).setCellValue("download_count");
        row.createCell(10).setCellValue("real_download_count");
        row.createCell(11).setCellValue("like_count");
        row.createCell(12).setCellValue("real_like_count");
    }
}
